#! /usr/bin/env python
# -*- coding: utf-8 -*-
# users.py
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes
* ignore
* limit
* channels
* url
"""
import re, time
from util.functions import *
from core.ircfuncs import is_channel, irc_lower

def users(bot, evt, cmd):
	""".users <#channel>. Show users of a given channel. Similar commands: .voiced, .opers"""
	ch = cmd.dict['chan'] or evt.chan or bot.defchan
	cmd = cmd.dict['cmd']
	try:
		if cmd == "users":
			users = bot.channels[ch].users()
		elif cmd == "opers":
			users = bot.channels[ch].opers()
		elif cmd == "voiced":
			users = bot.channels[ch].voiced()
		msg = join_userlist(users, bot.channels[evt.chan].users(), bot.channels[ch].lang)
	except KeyError:
		msg = "I'm not in this channel."
	except IndexError:
		msg = "There is no %s in this channel." % cmd
	bot.reply(evt, msg)
users.rule = re.compile("^($both)(?P<cmd>(?:(?:us|op)ers|voiced))(?: (?P<chan>#.+))?$")
users.showas = "users, opers, voiced"
users.fullmsg = True

def flags(bot, irc, cur):
	params = cur.params.strip()
	keys = params.split(" ")
	if len(keys)==2 or len(keys)==3:
		cmd = keys[0] if keys[0] in ("add","rem","mod","del") else ""
		target = keys[1] if cmd else keys[0]
		flags = keys[2] if cmd else keys[1]
		account = bot.account(irc.nick)
		if account == target or bot.accounts.has_flags(account, "d"):
			if not boss:
				bot.abuso.registracomando(nick,"flags",9)
				c.privmsg(canal, "no tiene los permisos necesarios")
				return
			if cur:
				usr=""
				flag=""
				if ":" in cur:
					usr=cur.split(":",1)[0].lower()
					flag=cur.split(":",1)[1]
				else:
					usr=cur.lower()
				if usr and flag:
					if usr not in flags:
						flags[usr]=flag
						c.privmsg(canal, "flags aceptados.")
					else:
						flags[usr]=flag
						c.privmsg(canal, "flags modificados.")
					desaReg()
				elif usr and not flag:
					if usr in flags:
						del flags[usr]
						c.privmsg(canal, "flags eliminados.")
						desaReg()
				else:
						c.privmsg(usuario, u"parámetros erróneos.")
flags.rule="flags"

def seen(bot, evt, cmd):
	""".seen <nick> - Reports when <nick> was last seen."""
	if not cmd.arguments:
		bot.reply(evt, "user was expected")
		return
	if not hasattr(bot, "seen"): return True
	m_nick = irc_lower(cmd.arguments)
	r_nick = cmd.arguments
	if bot.seen.has_key(m_nick):
		channel, t = bot.seen[m_nick]
		t = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(t))
		msg = "I last saw %s at %s on %s" % (r_nick, t, channel)
		bot.reply(evt, "$nick: %s" % msg)
	else:
		bot.reply(evt, "Sorry, I haven't seen %s around.", r_nick)
seen.rule = 'seen'

def wm_users(bot, evt, cmd):
	print "=== * === wm_users === * ==="
	chan = "#ca.wikipedia"
	if bot.label[0] == "master":
		u = bot.bots(("slave", 1)).channels[chan].users()
		mBot = bot.bots(("master", 0))
		bot.reply(evt, join_userlist(u, mBot.channels[mBot.defchan].users(), evt.lang))
	elif bot.label[1] == 1:
		u0 = bot.channels[chan].users()
		u1 = bot.bots(("master", 0)).channels[chan].users()
		bot.ctrl_msg(evt, join_userlist(u0, u1, evt.lang))
wm_users.rule = re.compile("^\?wm:u$")
wm_users.fullmsg = True

def note_(bot, evt, cmd):
	if not hasattr(bot, 'seen'):
		bot.seen = {}
	if is_channel(evt.target):
		if evt.target != bot.defchan:
			bot.seen[irc_lower(evt.source)] = (evt.target, time.time())
note_.rule = re.compile(".*")
note_.fullmsg = True
note_.evttypes = "*"
